package com.cl.pile.rule.func;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.cl.pile.rule.process.RuleMatcher;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * @author chenyitao
 * @date 2021/6/8
 */
public abstract class NumBaseFunc extends BaseFunc {

    public interface FuncCb {
        BigDecimal cb(BigDecimal oldNum, BigDecimal dataValue);
    }

    protected BigDecimal toNum(Object value) {
        if (value == null) {
            return null;
        }
        String sValue = String.valueOf(value);
        if (sValue.matches("-*\\d+(\\.\\d+)*")) {
            return new BigDecimal(sValue);
        }
        return null;
    }

    protected BigDecimal numFuncCb(BigDecimal startNum, List<Object> data, JSONObject ruleJson,
                                   RuleMatcher ruleMatcher, String var, Object root, FuncCb funcCb) {
        BigDecimal num = startNum;
        int index = 0;
        for (Object datum : data) {
            if (funcCb != null) {
                BigDecimal dv = toNum(datum);
                if (dv != null) {
                    if (ruleJson != null && ruleMatcher != null) {
                        int lastDotIndex = var.lastIndexOf(".");
                        // 截取parent获取path,并且指定下标精确获取
                        String parentVar = var.substring(0, lastDotIndex) + String.format("[%d]", index);
                        List<Object> parent = new ArrayList<>();
                        ruleMatcher.getJsonConvertUtil().getResultFromJson(root, parentVar, parent);
                        if (!parent.isEmpty()) {
                            JSONObject cpJson = new JSONObject();
                            if (ruleMatcher.matchRule(parent.get(0), ruleJson, cpJson, null,null,null)) {
                                BigDecimal nv = funcCb.cb(num, dv);
                                if (nv != null) {
                                    num = nv;
                                }
                            }
                        }
                    } else {
                        BigDecimal nv = funcCb.cb(num, dv);
                        if (nv != null) {
                            num = nv;
                        }
                    }
                }

                index++;
            }
        }
        return num;
    }
}
